/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.    
 */
package com.alapham.opens3.server;

import java.net.*;
import java.io.*;

public class Server {
	
	public static void main (String[] args)
    {
		//BatchBackup b = new BatchBackup();	
		//b.startBackup();
		
		//Create the server Socket
		 ServerSocket serverSocket = null;
		try {
		    serverSocket = new ServerSocket(5001);
		} catch (IOException e) {
		    System.out.println("Error listening on Port - 5001 - Exiting..");
		    System.exit(-1);
		}

		//Create the Client Socket
		Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Client Connection failed - Exiting...");
            System.exit(1);
        }
        
        Protocol s3protocol = new Protocol();
        PrintWriter out = null;
        BufferedReader in= null;
        String inputLine, outputLine;
        try {
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		} catch (IOException e) {
		    System.err.println("Error Connecting to Client - Exiting...");
            System.exit(1);
		}
       
		 outputLine = s3protocol.processInput(null);
	     out.println(outputLine);
	     
	     try{
		     while ((inputLine = in.readLine()) != null) {
	             outputLine = s3protocol.processInput(inputLine);
	             out.println(outputLine);
	             if (outputLine.equals("quit"))
	                break;
	        }
	     }
	     catch(IOException e)
	     {
	    	 System.err.println("Error Connecting to Client - Exiting...");
	         System.exit(1);
	     }
        out.close();
        try{
	        in.close();
	        clientSocket.close();
        }
        catch(IOException e)
        {
        	 System.err.println("Error Closing - Exiting...");
	         System.exit(1);
        }
    }
}
